<template>
    <!-- logs.wxml -->
    <view class="formContainer">
        <view class="centerRoot">
            <view class="topRoot">
                <view class="topTitle">
                    <image src="https://goverment-cdn.oss-cn-hangzhou.aliyuncs.com/assets/questionnaireTopLogo.png" mode="aspectFit" />
                </view>
                <view class="questionContainer">
                    <view :class="'question1 ' + (active === 1 ? 'active' : '') + ' ' + (active > 1 ? 'actived' : '')">
                        <view class="questionName">
                            <text>1、你从哪里了解这个新品</text>
                        </view>
                        <view :class="'questionParent  active' + q1">
                            <view class="questionItem" data-question="1" data-answer="1" @tap="questionOnClick">
                                <text>A. 此次活动</text>
                            </view>
                            <view class="questionItem" data-question="1" data-answer="2" @tap="questionOnClick">
                                <text>B. 电梯广告</text>
                            </view>
                            <view class="questionItem" data-question="1" data-answer="3" @tap="questionOnClick">
                                <text>C. 淘宝等网站</text>
                            </view>
                            <view class="questionItem" data-question="1" data-answer="4" @tap="questionOnClick">
                                <text>D. 其他</text>
                            </view>
                        </view>
                    </view>
                    <view :class="'question2 ' + (active === 2 ? 'active' : '') + ' ' + (active > 2 ? 'actived' : '')">
                        <view class="questionName">
                            <text>2、你买给谁吃</text>
                        </view>
                        <view :class="'questionParent  active' + q2">
                            <view class="questionItem" data-question="2" data-answer="1" @tap="questionOnClick">
                                <text>A. 自己</text>
                            </view>
                            <view class="questionItem" data-question="2" data-answer="2" @tap="questionOnClick">
                                <text>B. 孩子</text>
                            </view>
                            <view class="questionItem" data-question="2" data-answer="3" @tap="questionOnClick">
                                <text>C. 家人分享</text>
                            </view>
                        </view>
                    </view>
                    <view :class="'question3 ' + (active === 3 ? 'active' : '')">
                        <view class="questionName">
                            <text>3、你最被哪一点吸引</text>
                        </view>
                        <view :class="'questionParent  active' + q3">
                            <view class="questionItem" data-question="3" data-answer="1" @tap="questionOnClick">
                                <text>A. 经典奥利奥风味</text>
                            </view>
                            <view class="questionItem" data-question="3" data-answer="2" @tap="questionOnClick">
                                <text>B. 松松软软</text>
                            </view>
                            <view class="questionItem" data-question="3" data-answer="3" @tap="questionOnClick">
                                <text>C. 雪融般口感</text>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="bottomProgress">
                <text>游戏进度 {{ active }}/3</text>
                <view class="progressOuter">
                    <view class="progressInner" :style="'width: ' + (active - 1) * 48 + '%;'">
                        <image src="https://goverment-cdn.oss-cn-hangzhou.aliyuncs.com/assets/yui.svg" mode="aspectFit" />
                    </view>
                </view>
            </view>
        </view>
        <view class="bottomSubmit">
            <view class="bottomButton" @tap="onNext">
                <text>{{ active === 3 ? '提交问卷' : '下一步' }}</text>
            </view>
        </view>
        <view :class="'modal ' + (!success ? 'hidden' : '')">
            <view class="modal-musk"></view>
            <view class="modal-content">
                <view class="topTips">
                    <view class="content">
                        <image src="https://goverment-cdn.oss-cn-hangzhou.aliyuncs.com/assets/image%403x.png" mode="" />
                        <text class="text">填写完成，谢谢参与！</text>
                    </view>
                </view>
                <view class="bottomBtn">
                    <button @tap="confirm">确定</button>
                </view>
            </view>
        </view>
    </view>
</template>

<script lang="ts">
import { userLogin } from "@/services/utils";
// logs.ts

export default {
    data() {
        return {
            active: 1,
            q1: 0,
            q2: 0,
            q3: 0,
            success: false
        };
    },
    onLoad() {
        const paramsDeviceId = this.getParam()['device'];
        if (paramsDeviceId) {
          uni.setStorageSync('DEVICE_ID_PARAMS', paramsDeviceId);
        }
        this.handleLogin();
    },
    methods: {
        // 事件处理函数
        setData(datas) { 
          Object.keys(datas).map(item => {
            this[item] = datas[item]
          })
        },

        getDeviceId() {
          const storageId = uni.getStorageSync('DEVICE_ID_PARAMS');
          if (storageId) {
            return storageId;
          }
          return 1;
        },
        getParam(){
          let routes: { route: string, options?: { [key: string]: string } }[] = getCurrentPages(); // 获取当前打开过的页面路由数组
          let curParam = routes[routes.length - 1].options; //获取路由参数
          // 拼接参数
          return curParam
        },
        onNext() {
            // @ts-ignore
            if (!this['q' + this.active]) {
                uni.showToast({
                    title: '请选择',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }
            if (this.active === 3) {
                this.submitForm();
                // ====================== 下面是订阅相关代码
                console.log('开始订阅')
                const token = uni.getStorageSync('tokae_token');
                const oreotoken = uni.getStorageSync('TOKEN');
                const tmplIdMaps = {
                    // 'lbzNrR62vX79rfVyd0BCpwNjyGBHKK-iMdcTnTU9tOk': 'COUPON_RECEIVE',
                    // 'FQkxWfv5NgG6-8NV_OFOjguSheGDhaP5oI8E6PpJGTU': 'SURVEY_NOTIFY',
                    // 'bQOea6W7wWvgb-ORurr6uhiAXaP82kQqoG4QGYw--24': 'COUPON_EXPIRE'
                    [process.env.CLOUD_TMPL_RECEIVE]: 'COUPON_RECEIVE',
                    [process.env.CLOUD_TMPL_NOTIFY]: 'SURVEY_NOTIFY',
                    [process.env.CLOUD_TMPL_EXPIRE]: 'COUPON_EXPIRE'
                }
                uni.requestSubscribeMessage({
                  tmplIds: Object.keys(tmplIdMaps),
                  success: (res) => {
                    if (res) {
                      console.log('订阅成功', res)
                      const acceptValue = [];
                      Object.keys(tmplIdMaps).map((keyItem) => {
                        if (res[keyItem] === 'accept') {
                          acceptValue.push(tmplIdMaps[keyItem])
                        }
                      })
                      if (acceptValue.length) {
                        uni.request({
                          url: process.env.CLOUD_URL + '/questionnaire/subscribe?_=' + Date.now(),
                          method: 'POST',
                          header: {
                              authorization: token,
                              oreotoken,
                              device: this.getDeviceId()
                          },
                          data: {
                            scene: acceptValue
                          },
                          success: (res) => {
                            console.log(res);
                          }
                        })
                      } else {
                        console.log('用户拒绝了请求')
                      }
                    }
                  },
                  fail: (e) => {
                    console.log('订阅失败', e)
                  }
                })
            }
            this.setData({
                active: this.active + 1 > 3 ? 3 : this.active + 1
            });
        },

        submitForm() {
            const answer = {
                q1: this.q1,
                q2: this.q2,
                q3: this.q3
            };
            uni.showLoading({
                title: '请稍后'
            });
            const token = uni.getStorageSync('tokae_token');
            const oreotoken = uni.getStorageSync('TOKEN');
            uni.request({
                url: process.env.CLOUD_URL + '/questionnaire/pushUserRecord?_=' + Date.now(),
                method: 'POST',
                header: {
                    authorization: token,
                    oreotoken,
                    device: this.getDeviceId()
                },
                data: {
                    answer: JSON.stringify(answer),
                    doneFlag: !!answer.q3,
                    version: 1
                },
                success: (res: any) => {
                    if (res.data && res.data.success) {
                        this.setData({
                            success: true
                        });
                    } else {
                        uni.showToast({
                            icon: 'error',
                            title: '提交失败',
                            duration: 3000
                        });
                    }
                    uni.hideLoading();
                    if (res.statusCode === 401) {
                        this.handleLogin();
                    }
                },
                fail: (err: any): void => {
                    uni.hideLoading();
                    uni.showToast({
                        icon: 'error',
                        title: '游戏注册失败',
                        duration: 3000
                    });
                }
            });
        },

        getFormState() {
            const token = uni.getStorageSync('tokae_token');
            uni.request({
                url: process.env.CLOUD_URL + '/questionnaire/queryRecord?_=' + Date.now() + '&version=1',
                method: 'GET',
                header: {
                    authorization: token,
                    device: this.getDeviceId()
                },
                success: (res: any) => {
                    if (res.data && res.data.userid) {
                        // 查询到数据
                        let answer;
                        if (res.data.answer) {
                            answer = JSON.parse(res.data.answer);
                        } else {
                        }
                        const dataParams: any = {
                            success: res.data.doneFlag
                        };
                        if (answer) {
                            dataParams.q1 = answer.q1;
                            dataParams.q2 = answer.q2;
                            dataParams.q3 = answer.q3;
                            dataParams.active = answer.q3 ? 3 : answer.q2 ? 2 : 1;
                        }
                        if (res.data.doneFlag) {
                            this.setData(dataParams);
                        }
                    } else {
                        uni.showToast({
                            icon: 'error',
                            title: '查询失败',
                            duration: 3000
                        });
                    }
                    if (res.statusCode === 401) {
                        this.handleLogin();
                    }
                },
                fail: (err: any): void => {
                    uni.showToast({
                        icon: 'error',
                        title: '游戏注册失败',
                        duration: 3000
                    });
                }
            });
        },

        questionOnClick(event: any) {
            const question = event.currentTarget.dataset.question;
            const answer = event.currentTarget.dataset.answer;
            this.setData({
                ['q' + question]: answer
            });
        },

        async handleLogin() {
          this.runLogin();
        },

        

        registerUser() {
          return new Promise((resolve, reject) => {
            try {
              const loginParam: { type: number, code?: string } = {
                type: 1,
              };
              if (!uni.getStorageSync("OPENID")) {
                uni.login({
                  provider: "weixin",
                  success: async (res) => {
                    console.log(res);
                    loginParam.code = res.code;
                    const { data } = await userLogin(loginParam);
                    uni.setStorageSync("OPENID", data?.openId);
                    uni.setStorageSync("UNIONID", data?.unionId);
                    uni.setStorageSync("TOKEN", data?.accessToken);
                    resolve(res);
                  },
                  fail: (e) => {
                    reject(e)
                  }
                });
              } else {
                resolve(loginParam);
              }
            } catch (e) {
              reject(e);
            }
          })
        },

        async runLogin() {
          try {
            await this.registerUser()
          } catch (e) {
            uni.showToast({
              icon: 'error',
              title: '注册失败',
              duration: 3000
            });
          }

          uni.showLoading({
              title: '正在加载'
          });

          const userPhone = getApp().globalData.user.phone;
          
          if (userPhone) {
            // 是会员
            getApp().getUserInfo().then((user) => {
              const memberid = user.memberScore.memberId;
              this.loginByMemberId(memberid);
            }).catch((e) => {
              uni.showToast({
                icon: 'error',
                title: '注册失败',
                duration: 3000
              });
            });
          } else {
            // 不是会员
            getApp().getWechatUserProfile({
              path: '/packageTokaeGame/form/form?device=' + this.getDeviceId(),
              redirect: true
            })
          }
        },

        loginByMemberId(memberId: string) {
          return new Promise((resolve, reject) => {
            uni.request({
              method: 'POST',
              url: process.env.CLOUD_URL + '/user/loginByKaiJie',
              header: {
                device: this.getDeviceId()
              },
              data: {
                  memberid: memberId,
              },
              success: (res) => {
                  const result: any = res.data;
                  if (result) {
                      uni.setStorageSync('tokae_userInfo', result);
                      uni.setStorageSync('tokae_token', result.token);
                      this.getFormState();
                      resolve(result);
                  } else {
                      reject();
                  }
              },
              fail: () => {
                  uni.showToast({
                      icon: 'error',
                      title: '游戏注册失败',
                      duration: 3000
                  });
                  reject();
              }
            });
          })
        },

        confirmLogin() {
            const token = uni.getStorageSync('tokae_token');
            return new Promise((resolve, reject) => {
                uni.request({
                    url: process.env.CLOUD_URL + '/user/getUserInfo?_=' + Date.now(),
                    method: 'GET',
                    header: {
                        authorization: token,
                        device: this.getDeviceId()
                    },
                    success: (res: any) => {
                        if (res.data && res.data.token) {
                            uni.setStorageSync('tokae_userInfo', res.data);
                            uni.setStorageSync('tokae_token', res.data['tokae_token']);
                            this.getFormState();
                            resolve(res);
                        } else {
                            reject();
                        }
                        if (res.statusCode === 401) {
                            this.handleLogin();
                        }
                    },
                    fail: (err: any): void => {
                        reject();
                    }
                });
            });
        },

        confirm() {
            uni.reLaunch({
                url: '/pages/home/home'
            });
        }
    }
};
</script>
<style>
.formContainer {
    /* display: flex; */
    /* height: 100%; */
    /* align-items: center; */
}
.root {
    width: 100%;
}
.centerRoot {
    position: relative;
    height: 920rpx;
    margin: 190rpx 32rpx 0 32rpx;
    border-radius: 12px;
    background: linear-gradient(180deg, #52b7ff 0%, #1569e8 100%);
    box-shadow: inset -1px -2px 3px 0px #0054d3, 0px 0px 3px 0px #0054d3, inset 0px -2px 8px 0px #ffffff;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.topRoot {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    flex: 1;
}
.topTitle {
    /* padding: 64rpx 0; */
    width: 306rpx;
    height: 100rpx;
    position: relative;
    flex-shrink: 0;
}
.topTitle image {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 200rpx;
}
.questionContainer {
    margin-top: 56rpx;
    width: 480rpx;
    flex: 1;
    position: relative;
}
.questionContainer .question1,
.questionContainer .question2,
.questionContainer .question3 {
    position: absolute;
    top: 0;
    left: 0;
}
.questionContainer .question1 {
  transition: all 0.3s 0.3s;
}
.questionContainer .question2 {
    left: 144rpx;
    opacity: 0;
    /* transition: all 0.3s 0.3s; */
}
.questionContainer .question3 {
    left: 288rpx;
    opacity: 0;
    /* transition: all 0.3s 0.3s; */
}
.questionContainer .actived {
    left: -144rpx;
    opacity: 0;
    transition: all 0.3s 0.3s;
}
.questionContainer .active {
    left: 0;
    opacity: 1;
    z-index: 10;
    transition: all 0.3s 0.3s;
}
.questionName text {
    width: 100%;
    display: inline-block;
    text-align: center;
    position: relative;
    z-index: 3;
    font-family: Source Han Sans CN;
    font-size: 18px;
    font-weight: bold;
    text-align: center;
    color: #ffffff;
    text-shadow: 0 4px 12px rgba(13, 25, 102, 0.4);
}

.questionParent {
    margin-top: 54rpx;
}

.questionItem {
    width: 480rpx;
    height: 72rpx;
    border-radius: 36rpx;
    background: #93c7ff;
    display: flex;
    align-items: center;
    margin-bottom: 48rpx;
    transition: all 0.3s;
}
.questionItem text {
    padding: 0 32rpx;
    font-family: Source Han Sans CN;
    font-size: 14px;
    font-weight: 500;
    letter-spacing: 0em;
    color: #002c5d;
}
.questionParent.active1 .questionItem:nth-child(1) {
    background: #ffe269;
    z-index: 10;
}
.questionParent.active2 .questionItem:nth-child(2) {
    background: #ffe269;
    z-index: 10;
}
.questionParent.active3 .questionItem:nth-child(3) {
    background: #ffe269;
    z-index: 10;
}
.questionParent.active4 .questionItem:nth-child(4) {
    background: #ffe269;
    z-index: 10;
}
.questionItem.active text {
    color: #9c3506;
}
.bottomProgress {
    flex-shrink: 0;
    width: 480rpx;
    margin-bottom: 82rpx;
}
.bottomProgress text {
    font-family: Source Han Sans CN;
    font-size: 14px;
    font-weight: normal;
    color: #67b0ff;
}
.progressOuter {
    height: 16rpx;
    margin-top: 24rpx;
    background: rgba(17, 17, 17, 0.2);
    border-radius: 12rpx;
}
.progressInner {
    height: 100%;
    width: 0;
    border-radius: 12rpx;
    background: #67b0ff;
    position: relative;
    transition: all 0.2s 0.4s;
}
.progressInner image {
    position: absolute;
    right: -24rpx;
    bottom: 0;
    width: 48rpx;
    height: 38rpx;
}

.bottomSubmit {
    position: fixed;
    z-index: 10;
    left: 0;
    right: 0;
    bottom: 80rpx;
    display: flex;
    justify-content: center;
}
.bottomButton {
    width: 560rpx;
    height: 88rpx;
    border-radius: 44rpx;
    opacity: 1;
    background: linear-gradient(180deg, #ffd279 0%, #ffef5f 100%);
    box-shadow: inset 0px -5px 8px 0px rgba(203, 92, 0, 0.4), 0px 0px 8px 0px rgba(203, 92, 0, 0.4);
    font-size: 16px;
    font-weight: 500;
    text-align: center;
    color: #c74509;
    display: flex;
    align-items: center;
    justify-content: center;
}

.log-item {
    margin: 10rpx;
}

.modal {
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100;
}
.modal.hidden {
    display: none;
}
.modal .modal-musk {
    background-color: rgba(0, 0, 0, 0.7);
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    opacity: 1;
    transition: all 11s;
}
.modal.hidden .modal-musk {
    opacity: 0;
    transition: all 11s;
}
.modal .modal-content {
    width: 600rpx;
    height: 600rpx;
    background: #64a2ff;
    position: relative;
    z-index: 4;
    border-radius: 40rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    background: linear-gradient(0deg, #64a2ff 0%, #0968f7 100%);
}
.modal .modal-content .topTips {
    padding-top: 50rpx;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.modal .modal-content .topTips .content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-top: 32rpx;
}
.modal .modal-content .topTips image {
    height: 200rpx;
    width: 228rpx;
    position: relative;
    left: 12rpx;
}
.modal .modal-content .topTips .content .text {
    font-family: Source Han Sans CN;
    font-size: 18px;
    font-weight: 500;
    letter-spacing: 0em;
    margin-top: 36rpx;
    color: #ffffff;
}

.modal .modal-content .topTips .prize-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding-top: 94rpx;
    position: relative;
    width: 100%;
}
.modal .modal-content .topTips .prize-content .prizeImage {
    height: 40rpx;
}
.modal .modal-content .topTips .prize-content .prizeImage1 {
    width: 54rpx;
    height: 54rpx;
    position: absolute;
    right: 76rpx;
    top: 44rpx;
}
.modal .modal-content .topTips .prize-content .prizeImage2 {
    width: 54rpx;
    height: 86rpx;
    position: absolute;
    left: 60rpx;
    top: 92rpx;
}
.modal .modal-content .topTips .prize-content .noprize-text {
    font-size: 16px;
    font-weight: normal;
    text-align: center;
    letter-spacing: 0em;
    margin-top: 18rpx;
    color: #b1c2de;
}
.modal .modal-content .bottomBtn {
    padding-bottom: 48rpx;
}
.modal .modal-content .bottomBtn button {
    background: linear-gradient(180deg, #ffd279 0%, #ffef5f 100%);
    box-shadow: inset 0px -5px 8px 0px rgba(203, 92, 0, 0.4);
    width: 154px;
    height: 40px;
    border-radius: 24px;
    font-family: Source Han Sans CN;
    font-size: 16px;
    font-weight: 600;
    letter-spacing: 0em;
    color: #c74509;
}
</style>
